import { defineStore } from "pinia";
import { reqGetAuthorities, reqLogin, reqLogout, reqPostUpdateUserPassword, reqRegister, reqUserInfo } from "@/api/user"
import User from "@/class/User";
import { removeToken } from "@/utils/token";
import { successMessage } from "@/utils/message";
// 第一个参数是应用程序中 store 的唯一 id
export const useUserStore = defineStore('users', {
    state: () => {
        return {
            code: '',
            userInfo: new User({}),
            authorities: [] as string[],
        }
    },
    actions: {
        async userRegister(userData: User) {
            let result = await reqRegister(userData);
            this.userInfo = result.data
            return true
        },
        /**
         * 登录验证，保存结果
         * @param commit
         * @param loginData 登录的信息
         * @returns {Promise<boolean|*>}
         */
        async userLogin(loginData: User) {
            
            this.clearLoginInfo();
            let result = await reqLogin(loginData);
            this.getUserInfo();
            if (this.isLogin)
                successMessage("登录成功")
            return result
        },
        async getUserInfo() {
            if (this.isLogin)
                return 'ok';
            let result = await reqUserInfo();
            Object.assign(this.userInfo, result.data)
            if (this.isLogin) {                
                this.getAuthorities();
                return 'ok';
            } else {
                removeToken()
                return "not login";
            }
        },
        async logout() {
            this.clearLoginInfo()
            let result = await reqLogout();
            return result;
        },
        clearLoginInfo() {
            removeToken()
            this.$reset()
        },
        getAuthorities() {
            reqGetAuthorities().then((result) => {
                this.authorities = result.data
            })
        },
        async userSetPassword(password: string) {
            const result = await reqPostUpdateUserPassword({ password: password })
            return true;
        }
    },
    getters: {
        avatar(): any {
            const imageData = this.userInfo.header_pic || ''

            return imageData
            // return imageData.indexOf(',')>0 ? imageData : `data:image/jpg;base64,${imageData}`
        },
        isLogin(): boolean {
            return this.userInfo.id !== "" && this.userInfo.id !== undefined;
            // return true;
        },
        username(): string | undefined {
            return this.userInfo.username
        }
    }
})
